/// 我的资源页面
/// 
/// 用于管理用户创建的视频集合
/// 
/// @author Matrix
/// @version 1.0.0
/// @since 2025-11-26

import 'package:flutter/material.dart';
import '../../models/collection_model.dart';
import '../../services/collection_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'collection_detail_page.dart';
import '../publish/publish_collection_page.dart';

/// 我的资源页面
/// 
/// 显示用户创建的视频集合列表，支持创建、编辑、删除等操作
class MyResourcesPage extends StatefulWidget {
  const MyResourcesPage({super.key});

  @override
  State<MyResourcesPage> createState() => _MyResourcesPageState();
}

class _MyResourcesPageState extends State<MyResourcesPage> {
  /// 集合服务
  final CollectionService _collectionService = CollectionService();
  
  /// 集合列表
  List<CollectionModel> _collections = [];
  
  /// 是否正在加载
  bool _isLoading = false;
  
  /// 是否有更多数据
  bool _hasMore = true;
  
  /// 当前页码
  int _currentPage = 1;
  
  /// 每页数量
  static const int _pageSize = 20;
  
  /// 当前筛选状态
  String? _currentStatus;
  
  /// 是否是VIP用户
  bool _isVip = false;

  @override
  void initState() {
    super.initState();
    _checkVipAndLoad();
  }

  /// 检查VIP状态并加载数据
  Future<void> _checkVipAndLoad() async {
    try {
      // 检查VIP状态
      _isVip = await _collectionService.checkVipStatus();
      Logger.d('MY_RESOURCES', 'VIP状态: $_isVip');
    } catch (e) {
      Logger.e('MY_RESOURCES', '检查VIP状态失败: $e');
      // 默认不是VIP
      _isVip = false;
    }
    
    // 加载集合列表
    _loadCollections(refresh: true);
  }

  /// 加载集合列表
  Future<void> _loadCollections({bool refresh = false}) async {
    if (_isLoading) return;
    if (!refresh && !_hasMore) return;

    setState(() => _isLoading = true);

    try {
      if (refresh) {
        _currentPage = 1;
        _hasMore = true;
      }

      final result = await _collectionService.getMyCollections(
        page: _currentPage,
        pageSize: _pageSize,
        status: _currentStatus,
      );

      setState(() {
        if (refresh) {
          _collections = result.records;
        } else {
          _collections.addAll(result.records);
        }
        _hasMore = result.hasMore;
        if (result.hasMore) {
          _currentPage++;
        }
        _isLoading = false;
      });

      Logger.d('MY_RESOURCES', '加载成功，共 ${_collections.length} 个集合');
    } catch (e) {
      Logger.e('MY_RESOURCES', '加载集合列表失败: $e');
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载失败: $e')),
        );
      }
    }
  }

  /// 刷新列表
  Future<void> _refresh() async {
    await _loadCollections(refresh: true);
  }

  /// 创建新集合
  void _createCollection() {
    // 检查VIP状态
    if (!_isVip) {
      _showVipRequiredDialog();
      return;
    }

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const PublishCollectionPage(),
      ),
    ).then((result) {
      if (result == true) {
        _refresh();
      }
    });
  }

  /// 显示需要VIP的对话框
  void _showVipRequiredDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.workspace_premium, color: Colors.amber),
            SizedBox(width: 8),
            Text('VIP专属功能'),
          ],
        ),
        content: const Text('发布视频集合是VIP会员专属功能。\n\n升级VIP后，您可以：\n• 创建和管理视频集合\n• 设置白名单访问权限\n• 推广您的内容获取更多曝光'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('暂不升级'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              // 第一版：直接开通VIP，跑通流程
              await _activateVip();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.amber,
            ),
            child: const Text('立即开通VIP'),
          ),
        ],
      ),
    );
  }

  /// 开通VIP（第一版：直接开通，跑通流程）
  Future<void> _activateVip() async {
    try {
      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );

      // 调用后端开通VIP接口
      await _collectionService.activateVip();

      // 关闭加载提示
      if (mounted) Navigator.pop(context);

      // 更新VIP状态
      setState(() {
        _isVip = true;
      });

      // 显示成功提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('🎉 恭喜！VIP开通成功！'),
            backgroundColor: Colors.green,
          ),
        );
      }

      Logger.d('MY_RESOURCES', 'VIP开通成功');
    } catch (e) {
      // 关闭加载提示
      if (mounted) Navigator.pop(context);

      Logger.e('MY_RESOURCES', 'VIP开通失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('VIP开通失败: $e')),
        );
      }
    }
  }

  /// 查看集合详情
  void _viewCollection(CollectionModel collection) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => CollectionDetailPage(collection: collection),
      ),
    ).then((result) {
      if (result == true) {
        _refresh();
      }
    });
  }

  /// 编辑集合
  void _editCollection(CollectionModel collection) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PublishCollectionPage(collection: collection),
      ),
    ).then((result) {
      if (result == true) {
        _refresh();
      }
    });
  }

  /// 删除集合
  void _deleteCollection(CollectionModel collection) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除集合'),
        content: Text('确定要删除集合"${collection.title}"吗？\n\n删除后，集合内的所有视频都将被移除，此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              try {
                await _collectionService.deleteCollection(collection.id);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('删除成功')),
                );
                _refresh();
              } catch (e) {
                Logger.e('MY_RESOURCES', '删除集合失败: $e');
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('删除失败: $e')),
                );
              }
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 切换筛选状态
  void _changeStatusFilter(String? status) {
    if (_currentStatus == status) return;
    setState(() => _currentStatus = status);
    _loadCollections(refresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 顶部操作栏
        _buildHeader(),
        
        // 筛选标签
        _buildFilterTabs(),
        
        // 集合列表
        Expanded(
          child: _buildCollectionList(),
        ),
      ],
    );
  }

  /// 构建顶部操作栏
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              const Text(
                '我的资源',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(width: 8),
              // VIP标识
              if (_isVip)
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Colors.amber, Colors.orange],
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Text(
                    'VIP',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
            ],
          ),
          ElevatedButton.icon(
            onPressed: _createCollection,
            icon: const Icon(Icons.add, size: 18),
            label: const Text('新建集合'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建筛选标签
  Widget _buildFilterTabs() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          _buildFilterChip('全部', null),
          const SizedBox(width: 8),
          _buildFilterChip('已发布', 'published'),
          const SizedBox(width: 8),
          _buildFilterChip('草稿', 'draft'),
          const SizedBox(width: 8),
          _buildFilterChip('已隐藏', 'hidden'),
        ],
      ),
    );
  }

  /// 构建筛选标签
  Widget _buildFilterChip(String label, String? status) {
    final isSelected = _currentStatus == status;
    return GestureDetector(
      onTap: () => _changeStatusFilter(status),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: isSelected ? Theme.of(context).primaryColor : Colors.grey[200],
          borderRadius: BorderRadius.circular(16),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey[700],
            fontSize: 13,
          ),
        ),
      ),
    );
  }

  /// 构建集合列表
  Widget _buildCollectionList() {
    if (_isLoading && _collections.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_collections.isEmpty) {
      return _buildEmptyState();
    }

    return RefreshIndicator(
      onRefresh: _refresh,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _collections.length + (_hasMore ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _collections.length) {
            // 加载更多
            if (_hasMore && !_isLoading) {
              _loadCollections();
            }
            return const Center(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: CircularProgressIndicator(),
              ),
            );
          }
          return _buildCollectionCard(_collections[index]);
        },
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.video_library_outlined,
            size: 80,
            color: Colors.grey[300],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无视频集合',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _isVip ? '点击"新建集合"创建您的第一个视频集合' : '升级VIP后可创建视频集合',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[400],
            ),
          ),
          const SizedBox(height: 24),
          if (_isVip)
            ElevatedButton.icon(
              onPressed: _createCollection,
              icon: const Icon(Icons.add),
              label: const Text('新建集合'),
            )
          else
            ElevatedButton.icon(
              onPressed: _showVipRequiredDialog,
              icon: const Icon(Icons.workspace_premium),
              label: const Text('升级VIP'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.amber,
              ),
            ),
        ],
      ),
    );
  }

  /// 构建集合卡片
  Widget _buildCollectionCard(CollectionModel collection) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: InkWell(
        onTap: () => _viewCollection(collection),
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 封面图
              ClipRRect(
                borderRadius: BorderRadius.circular(6),
                child: CachedImageWidget(
                  imageUrl: collection.coverUrl,
                  width: 100,
                  height: 75,
                  fit: BoxFit.cover,
                  imageType: '集合封面',
                ),
              ),
              const SizedBox(width: 12),
              
              // 集合信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题和状态
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            collection.title,
                            style: const TextStyle(
                              fontSize: 15,
                              fontWeight: FontWeight.w600,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        _buildStatusBadge(collection.status),
                      ],
                    ),
                    const SizedBox(height: 4),
                    
                    // 描述
                    if (collection.description != null && collection.description!.isNotEmpty)
                      Text(
                        collection.description!,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey[600],
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 8),
                    
                    // 统计信息
                    Row(
                      children: [
                        _buildStatItem(Icons.video_library, '${collection.videoCount}个视频'),
                        const SizedBox(width: 16),
                        _buildStatItem(Icons.visibility, '${collection.viewsCount}浏览'),
                        const SizedBox(width: 16),
                        if (collection.isWhitelist)
                          _buildStatItem(Icons.lock, '白名单'),
                      ],
                    ),
                    const SizedBox(height: 8),
                    
                    // 推荐标识
                    if (collection.isRecommended)
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.orange[100],
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.trending_up, size: 14, color: Colors.orange[700]),
                            const SizedBox(width: 4),
                            Text(
                              '推广中',
                              style: TextStyle(
                                fontSize: 11,
                                color: Colors.orange[700],
                              ),
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
              
              // 操作菜单
              PopupMenuButton<String>(
                icon: Icon(Icons.more_vert, color: Colors.grey[600]),
                onSelected: (value) {
                  switch (value) {
                    case 'edit':
                      _editCollection(collection);
                      break;
                    case 'delete':
                      _deleteCollection(collection);
                      break;
                    case 'publish':
                      _publishCollection(collection);
                      break;
                    case 'hide':
                      _hideCollection(collection);
                      break;
                  }
                },
                itemBuilder: (context) => [
                  const PopupMenuItem(
                    value: 'edit',
                    child: Row(
                      children: [
                        Icon(Icons.edit, size: 18),
                        SizedBox(width: 8),
                        Text('编辑'),
                      ],
                    ),
                  ),
                  if (collection.status == 'draft')
                    const PopupMenuItem(
                      value: 'publish',
                      child: Row(
                        children: [
                          Icon(Icons.publish, size: 18),
                          SizedBox(width: 8),
                          Text('发布'),
                        ],
                      ),
                    ),
                  if (collection.status == 'published')
                    const PopupMenuItem(
                      value: 'hide',
                      child: Row(
                        children: [
                          Icon(Icons.visibility_off, size: 18),
                          SizedBox(width: 8),
                          Text('隐藏'),
                        ],
                      ),
                    ),
                  const PopupMenuItem(
                    value: 'delete',
                    child: Row(
                      children: [
                        Icon(Icons.delete, color: Colors.red, size: 18),
                        SizedBox(width: 8),
                        Text('删除', style: TextStyle(color: Colors.red)),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建状态标签
  Widget _buildStatusBadge(String status) {
    Color bgColor;
    Color textColor;
    String text;

    switch (status) {
      case 'published':
        bgColor = Colors.green[100]!;
        textColor = Colors.green[700]!;
        text = '已发布';
        break;
      case 'draft':
        bgColor = Colors.grey[200]!;
        textColor = Colors.grey[700]!;
        text = '草稿';
        break;
      case 'hidden':
        bgColor = Colors.orange[100]!;
        textColor = Colors.orange[700]!;
        text = '已隐藏';
        break;
      default:
        bgColor = Colors.grey[200]!;
        textColor = Colors.grey[700]!;
        text = '未知';
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 11,
          color: textColor,
        ),
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(IconData icon, String text) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 14, color: Colors.grey[500]),
        const SizedBox(width: 4),
        Text(
          text,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  /// 发布集合
  Future<void> _publishCollection(CollectionModel collection) async {
    try {
      await _collectionService.updateCollection(
        id: collection.id,
        status: 'published',
      );
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('发布成功')),
      );
      _refresh();
    } catch (e) {
      Logger.e('MY_RESOURCES', '发布失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('发布失败: $e')),
      );
    }
  }

  /// 隐藏集合
  Future<void> _hideCollection(CollectionModel collection) async {
    try {
      await _collectionService.updateCollection(
        id: collection.id,
        status: 'hidden',
      );
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('已隐藏')),
      );
      _refresh();
    } catch (e) {
      Logger.e('MY_RESOURCES', '隐藏失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('隐藏失败: $e')),
      );
    }
  }
}
